package nl.nhl.idp.Components;

import android.os.Handler;

public class Timer
{
	public static String ParseMillisecs(long milliseconds)
	{
		int mins = (int)(milliseconds/60000);
		int secs = (int)((milliseconds-mins*60000)/1000);
		int msecs = (int)((milliseconds-(mins*60000+secs*1000)));
		
		String m = mins+"";
		if( m.length() == 1)
			m = '0'+m;
		String s = secs+"";
		if( s.length() == 1)
			s = '0'+s;
		String ms = msecs+"";
		if( ms.length() == 1)
			ms = '0'+ms;
		else if(ms.length() > 2)
			ms = ms.substring(0, 2);
		
		return (m+":"+s+":"+ms);
	}
	
	private Handler timerHandler;
	private TimerListener listener;
	private TimerTick tickAction;
	private long interval;
	private long startTime;

	public boolean IsStarted()
	{
		return (timerHandler != null);
	}
	
	public long ElapsedTime()
	{
		if(this.IsStarted())
			return System.currentTimeMillis()-startTime;
		else
			return 0;
	}
	
	/**
	 * Creates a new threadless timer, this timer runs on the thread it is made on, and will thus not have cross-thread call problems.
	 * @param listener The object that listens for TimerTickListener events.
	 * @param interval The interval at which teh timer should tick.
	 */
	public Timer(TimerListener listener, long interval)
	{
		this.listener = listener;
		this.interval = interval;
	}
	
	/**
	 * Starts the Timer from zero
	 */
	public void start()
	{
		startTime = System.currentTimeMillis();
		timerHandler = new Handler();
		tickAction = new TimerTick();
		timerHandler.removeCallbacks(tickAction);
		timerHandler.postDelayed(tickAction, interval);
	}
	
	/**
	 * Stops the Timer.
	 */
	public void stop()
	{
		timerHandler.removeCallbacks(tickAction);
		timerHandler = null;
	}
	
	public class TimerTick implements Runnable
	{
		public void run()
		{
			if(listener != null)
				listener.OnTick(System.currentTimeMillis()-startTime);
			
			timerHandler.postDelayed(this, interval);
		}
	}
}
